package com.inter.utils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public class HMACSHA256 {
  /**     
  * 将加密后的字节数组转换成字符串   
  *    
  * @param b 字节数组    
  * @return 字符串     
  */   
 private static String byteArrayToHexString(byte[] b) {  
      StringBuilder hs = new StringBuilder();     
      String stmp;      
  for (int n = 0; b!=null && n < b.length; n++) {   
         stmp = Integer.toHexString(b[n] & 0XFF);    
         if (stmp.length() == 1)   {
             hs.append('0');
         }

         hs.append(stmp);    
    }      
   return hs.toString().toLowerCase();   
 }   
 /**   
  * sha256_HMAC加密    
  * @param message 消息   
  * @param secret  秘钥 
  * @return 加密后字符串  
  */  
  public static String sha256_HMAC(String message, String secret) {     
   String hash = "";      
   try {         
       Mac sha256_HMAC = Mac.getInstance("HmacSHA256");     
       SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");      
       sha256_HMAC.init(secret_key);       
       byte[] bytes = sha256_HMAC.doFinal(message.getBytes());   
       hash = byteArrayToHexString(bytes);         
       System.out.println(hash);    
       } catch (Exception e) {     
       System.out.println("Error HmacSHA256 ===========" + e.getMessage());   
     }       
    return hash;   
   }


    /**
     * 测试方法
     *
     * @param args
     */
    public static void main(String[] args) throws Exception {
        String secureCode="4J6fb4668dz4np44pvVzNZ488bF6r6Db248frX6Z0B24z8rLt8fT0dFRx0pt4X8d";
		StringBuffer buffer1 = new StringBuffer();// 专门用于签名拼接使用
		buffer1.append("181152");
		buffer1.append("18115201");
		buffer1.append("https://wx.linksfield.net/#/paySuccess");
		buffer1.append("201903141053");
        buffer1.append("USD");
        buffer1.append("1.00");
        buffer1.append("liu");
        buffer1.append("min");
        buffer1.append("133@qq.com");
        buffer1.append("4J6fb4668dz4np44pvVzNZ488bF6r6Db248frX6Z0B24z8rLt8fT0dFRx0pt4X8d");
		String str1 = buffer1.toString();
		System.out.println(str1);
		// 签名结果：84dNMbfgjLMS42IqSTPqQ99cUGA=
		System.out.println(sha256_HMAC(str1,secureCode));
    }

 }
